import 'dart:async';

import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/home_main_controller.dart';

import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/routers/routers.dart';
import 'package:dmz/user/user_defurl.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:dmz/utils/oss_utils.dart';
import 'package:dmz/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import '../../../utils/preference_utils.dart';
import 'mine_main_controller.dart';

class SetingMainController extends BaseController {
  TextEditingController textController = TextEditingController();
  TextEditingController setPhoneNumCt = TextEditingController();
  TextEditingController setPhoneCodeCt = TextEditingController();
  TextEditingController setPassWordACt = TextEditingController();
  TextEditingController setPassWordBCt = TextEditingController();
  TextEditingController setPassWordCCt = TextEditingController();
  TextEditingController setFeedbackCt = TextEditingController();

  BuildContext? context;

  Timer? timer;
  RxInt counter = 60.obs;
  RxInt snedCodeType = 0.obs;

  late MotoModel moto;

  int setingID = 0;

  List<bool> messageTypes = [false, false, false, false, false];
  List<String> typeKeys = [
    'vibration',
    'cut_power',
    'charge_monitor',
    'guard_alarm',
    'fault_alarm'
  ];
  List<AssetEntity> imagesDatas = [];
  String vison = '';
  Map<String, dynamic>? parameters;

  @override
  void loadNet() {}

  @override
  void onHidden() {}

  @override
  void onInit() {
    var controller = Get.find<HomePageController>();
    moto = controller.motoList[controller.pageIndex];
    if (moto.socket_type == 1) getSetingData();
    super.onInit();
  }

  cleanTextTextEditing() {
    textController.text = setPhoneNumCt.text = setPhoneCodeCt.text =
        setPassWordACt.text =
            setPassWordBCt.text = setPassWordCCt.text = setFeedbackCt.text = '';
  }

  getSetingData() {
    RequestClient().post<Map>(APIS.userSeting, data: {}).then((value) {
      debugPrint('设置信息返回 --- $value');
      messageTypes[0] = value?['vibration'] == 1;
      messageTypes[1] = value?['cut_power'] == 1;
      messageTypes[2] = value?['charge_monitor'] == 1;
      messageTypes[3] = value?['guard_alarm'] == 1;
      messageTypes[4] = value?['fault_alarm'] == 1;
      setingID = value?['id'];
      update(['setMain']);
    });
  }

  ///tag 0'头像', 1'昵称', 2'更换手机号', 3'修改登录密码', 4'指纹登录'
  ///tag 5'异常震动', 6'切断电源', 7'充电检测', 8'防盗报警', 9'故障消息'
  ///tag 10'多语言切换', 11'意见反馈', 12'关于我们', 13'注销账号' 14'确认上报'
  pageAction(int tag) async {
    switch (tag) {
      case 0:
        changeHeadImage();
        break;
      case 1:
        textController.text = EMIBUserManger().user?.name ?? '';
        Get.toNamed(RouteGet.setingName);
        break;
      case 2:
        Get.toNamed(RouteGet.setingPhone);
        break;
      case 3:
        cleanTextTextEditing();
        Get.toNamed(RouteGet.setingPassword);
        break;
      case 4: //face ID
        break;
      case 5:
        changeMessageAction(tag - 5);
        break;
      case 6:
        changeMessageAction(tag - 5);
        break;
      case 7:
        changeMessageAction(tag - 5);
        break;
      case 8:
        changeMessageAction(tag - 5);
        break;
      case 9:
        changeMessageAction(tag - 5);
        break;
      case 10:
        Get.toNamed(RouteGet.changeLanguage);
        break;
      case 11:
        Get.toNamed(RouteGet.setingFeedback);
        break;
      case 12:
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        debugPrint('当前版本 --- ${packageInfo.version}');
        vison = packageInfo.version;
        Get.toNamed(RouteGet.setingAboutUs);
        break;
      case 13:
        didLogoutAll();
        break;
      case 14:
        EMIBUserManger().logout();
        break;
      case 15:
        EMIBUserManger().launchURL(0);
        break;
      case 16:
        EMIBUserManger().launchURL(1);
        break;
      case 17: //注销账号
        EMIBUserManger().launchURL(1);
        break;

      default:
    }
  }

  ///修改昵称
  changeName() async {
    if (textController.text.isEmpty) return EMILoding.hitLoding('请输入新的昵称');
    await changeUserInfor(1, textController.text);
    EMIBUserManger().user?.name = textController.text;
    EMIBUserManger().upadtaSave();
    EMILoding.hitLoding('修改成功'.tr, isScuess: true);
    Get.back();
    update(['setMain']);
  }

  Future<void> changeUserInfor(int tag, dynamic conten) async {
    await RequestClient()
        .post<Map>(APIS.changeUser, data: {getNetKey(tag): conten});
  }

  getNetKey(int tag) {
    switch (tag) {
      case 1:
        return 'name';
      case 2:
        return 'picture';
      default:
    }
  }

  void startTimer() {
    snedCodeType.value = 1;
    const oneSec = Duration(seconds: 1);
    timer?.cancel();
    timer = Timer.periodic(
      oneSec,
      (Timer timer) {
        if (counter.value == 0) {
          timer.cancel();
          counter.value = 60;
          snedCodeType.value = 2;
        } else {
          counter.value--;
        }
      },
    );
  }

  ///发送验证码
  snedCode() {
    if (setPhoneNumCt.text.isEmpty) return EMILoding.hitLoding('手机号不能为空');
    if (snedCodeType.value == 1) return;
    startTimer();
    RequestClient().post(APIS.getCode, data: {'phone': setPhoneNumCt.text},
        onError: (error) {
      if (error.code != 0) {
        EMILoding.hitLoding('发送失败请稍后重试'.tr);
      }
      return false;
    }).then((value) {
      EMILoding.hitLoding('发送成功'.tr, isScuess: true);
    });
  }

  ///更改手机号
  changePhone() {
    if (setPhoneNumCt.text.isEmpty) return EMILoding.hitLoding('手机号不能为空'.tr);
    if (setPhoneCodeCt.text.isEmpty) return EMILoding.hitLoding('验证码不能为空'.tr);
    RequestClient().post(APIS.changePhone, data: {
      'phone': setPhoneNumCt.text,
      'code': int.parse(setPhoneCodeCt.text)
    }).then((value) {
      EMILoding.hitLoding('修改成功'.tr, isScuess: true);
      EMIBUserManger().user?.phone = setPhoneNumCt.text;
      EMIBUserManger().upadtaSave();
      update(['setMain']);
      Get.back();
    });
  }

  ///修改密码
  changePassWord() {
    var isSetPassword = EMIBUserManger().user?.password_set ?? false;
    if (!isSetPassword && setPhoneCodeCt.text.isEmpty) {
      return EMILoding.hitLoding('请输入验证码'.tr);
    }

    if ((!SPUtils.validatePassword(setPassWordACt.text) ||
            !SPUtils.validatePassword(setPassWordBCt.text) ||
            !SPUtils.validatePassword(setPassWordCCt.text)) &&
        isSetPassword) {
      return EMILoding.hitLoding('密码由8-16位数字、字母或符号组成，至少含有两种字符以上'.tr);
    }

    if ((!SPUtils.validatePassword(setPassWordBCt.text) ||
            !SPUtils.validatePassword(setPassWordCCt.text)) &&
        !isSetPassword) {
      return EMILoding.hitLoding('密码由8-16位数字、字母或符号组成，至少含有两种字符以上'.tr);
    }

    if (setPassWordBCt.text == setPassWordACt.text ||
        setPassWordCCt.text == setPassWordACt.text) {
      return EMILoding.hitLoding('新密码不能与旧密码相同'.tr);
    }

    if (setPassWordBCt.text.isEmpty || setPassWordCCt.text.isEmpty) {
      return EMILoding.hitLoding('新密码不能为空'.tr);
    }

    if (setPassWordBCt.text != setPassWordCCt.text) {
      return EMILoding.hitLoding('新密码两次输入不一致'.tr);
    }

    RequestClient()
        .post(isSetPassword ? APIS.changeNewPassword : APIS.setPassword,
            data: isSetPassword
                ? {
                    'password_old': setPassWordACt.text,
                    'password_new': setPassWordBCt.text
                  }
                : {
                    'code': int.parse(setPhoneCodeCt.text),
                    'password': setPassWordBCt.text
                  })
        .then((value) {
      EMILoding.hitLoding('修改成功'.tr, isScuess: true);
      if (isSetPassword) {
        EMIBUserManger().logout();
      } else {
        EMIBUserManger().user?.password_set = true;
        update(['setMain']);
        Get.back();
      }
    });
  }

  ///更换头像
  changeHeadImage() async {
    OssUtils.initOss();
    List<AssetEntity>? result = await AssetPicker.pickAssets(
      context!,
      pickerConfig: const AssetPickerConfig(maxAssets: 1),
    );
    if (result != null && result.isNotEmpty) {
      var byteData = await result[0].originBytes;
      OssUtils.updataImages(byteData!).then((data) {
        if (data != null) {
          EMIBUserManger().user?.picture = data;
          EMIBUserManger().upadtaSave();
          changeUserInfor(2, data);
          update(['setMain']);
          Get.find<MinePageController>().update();
        }
      });
    }
  }

  changeMessageAction(tag) {
    RequestClient().post<Map>(APIS.changeSeting, data: {
      'id': setingID,
      typeKeys[tag]: messageTypes[tag] ? 0 : 1
    }).then((value) {
      messageTypes[tag] = !messageTypes[tag];
      update(['setMain']);
    });
  }

  ///意见反馈选择图片
  feedbackSelectImages() async {
    List<AssetEntity>? result = await AssetPicker.pickAssets(
      context!,
      pickerConfig: AssetPickerConfig(maxAssets: 6 - imagesDatas.length),
    );
    if (result != null && result.isNotEmpty) {
      imagesDatas = result;
      update(['feedBack']);
    }
  }

  ///意见反馈删除图片
  delectImageIndex(index) {
    imagesDatas.removeAt(index);
    update(['feedBack']);
  }

  feedbackInputChnage() {
    if (setFeedbackCt.text.length > 500) {
      var str = setFeedbackCt.text.substring(0, 500);
      setFeedbackCt.text = str;
    }
    update(['feedBack']);
  }

  feedbackUpdata() async {
    if (setFeedbackCt.text.isEmpty) return EMILoding.hitLoding('请填写反馈内容');
    EMILoding.didLoding();
    await OssUtils.initOss();
    List<List<int>> result = [];
    for (var element in imagesDatas) {
      var data = await element.originBytes;
      if (data != null) result.add(data);
    }
    parameters ??= {};
    parameters?['type'] = 1;
    parameters?['details'] = setFeedbackCt.text;
    parameters?['phone'] = EMIBUserManger().user?.phone ?? '';

    if (result.isNotEmpty && parameters?['photo'] == null) {
      var imageStrs = await OssUtils.updataMoreImages(result);
      parameters?['images'] = imageStrs;
    }

    RequestClient().post(APIS.feedbackCreate, data: parameters).then((value) {
      imagesDatas.clear();
      EMILoding.hitLoding('反馈成功'.tr, isScuess: true);
      Get.back();
    });
  }

  didLogoutAll() {
    EMILoding.showBottomHitWindow('温馨提示'.tr, '注销账号后，您将无法登录'.tr, (agree) {
      Get.back();
      if (!agree) return;
      RequestClient().post(APIS.delectUser, data: {}).then((value) {
        EMIBUserManger().logout();
      });
    });
  }

  getSelectIndex() {
    var code = Get.locale?.languageCode;
    switch (code) {
      case 'en':
        return 0;
      case 'zh':
        return 1;
      case 'th':
        return 2;
      default:
        return -1;
    }
  }

  changeLanguaged(int index) {
    switch (index) {
      case 0:
        PreferenceUtils().putString('language', 'en,EN');
        Get.updateLocale(const Locale('en', 'EN'));
        break;
      case 1:
        PreferenceUtils().putString('language', 'zh,CN');
        Get.updateLocale(const Locale('zh', 'CN'));
        break;
      case 2:
        PreferenceUtils().putString('language', 'th,TH');
        Get.updateLocale(const Locale('th', 'TH'));
        break;
      default:
    }

    update(['language']);
  }

  @override
  void dispose() {
    timer?.cancel();
    super.dispose();
  }
}
